package com.lcj.dr.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.IdUtil;
import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lcj.common.exception.AochException;
import com.lcj.dr.controller.form.WalletPageForm;
import com.lcj.dr.controller.form.DriverRechargeForm;
import com.lcj.dr.db.dao.WalletDao;
import com.lcj.dr.db.dao.WalletIncomeDao;
import com.lcj.dr.db.pojo.WalletEntity;
import com.lcj.dr.db.pojo.WalletIncomeEntity;
import com.lcj.dr.service.WalletIncomeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;

@Service
@Slf4j
public class WalletIncomeServiceImpl implements WalletIncomeService {

    @Resource
    private WalletIncomeDao walletIncomeDao;

    @Resource
    private WalletDao walletDao;

    @Override
    @Transactional
    @LcnTransaction
    public int transfer(WalletIncomeEntity entity) {
        //添加转账记录
        int rows = walletIncomeDao.insert(entity);
        if (rows != 1) {
            throw new AochException("添加转账记录失败");
        }

        HashMap param = new HashMap();
        param.put("driverId", entity.getDriverId());
        param.put("amount", entity.getAmount());

        //更新帐户余额
        rows = walletDao.updateWalletBalanceNoPassword(param);
        if (rows != 1) {
            throw new AochException("更新钱包余额失败");
        }
        return rows;
    }

    @Override
    public PageInfo<WalletEntity> searWalletIncomeByPage(WalletPageForm walletPageForm) {
        PageHelper.startPage(walletPageForm.getPage(), walletPageForm.getLength());
        List<WalletIncomeEntity> list = walletIncomeDao.queryList();
        PageInfo<WalletEntity> pageInfo = new PageInfo(list);
        return pageInfo;
    }

    @Override
    @Transactional
    @LcnTransaction
    public int recharge(DriverRechargeForm form) {
        HashMap param = new HashMap();
        param.put("driverId", form.getDriverId());
        param.put("amount", form.getAmount());
        int rows = walletDao.updateWalletBalanceNoPassword(param);
        if(rows > 0) {
            WalletIncomeEntity walletIncomeEntity = new WalletIncomeEntity();
            walletIncomeEntity.setUuid(IdUtil.simpleUUID());
            walletIncomeEntity.setDriverId(form.getDriverId());
            walletIncomeEntity.setType((byte) 2);
            walletIncomeEntity.setStatus((byte) 3);
            walletIncomeEntity.setAmount(BigDecimal.valueOf(form.getAmount()));
            walletIncomeEntity.setRemark("司机充值");
            walletIncomeEntity.setCreateTime(new DateTime().toString());
            walletIncomeDao.insert(walletIncomeEntity);
        }
        return rows;
    }
}